<?php
namespace app\api\controller;
use app\common\controller\ApiAction;
/**
 * @Class: Login
 * @Description: todo(登陆换取token)
 */
class Login extends ApiAction
{
	/**
     * @Title: getToken
     * @Description: todo(获取用户登陆态)
     * @param int $code 微信登录凭证
     * @return json
     * @author 若谷
     * @date 2019年5月22日
     * @throws
     */
    public function getToken(){
        $code = input("post.code");
        if(!$code){
            return $this->response(lang('fail_code'),'参数错误','缺少参数');
        }
        $appid  = confv('wx_appid');
        $secret = confv('wx_secret');
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$secret."&js_code=".$code."&grant_type=authorization_code";
        $res = curl_post($url);
        if($res){
            $res = json_decode($res,true);
            if (isset($res['openid'])) {
            	$token = $this->login($res['openid']);
            	if ($token) {
            		return $this->response(lang('success_code'),'登陆成功',$token);
            	}else{
            		return $this->response(lang('fail_code'),'该用户被禁止使用！');
            	}
            }else{
                return $this->response(lang('fail_code'),'登陆失败',$res);
            }
        }else{
            return $this->response(lang('fail_code'),'链接失败');
        }
    }

    /**
     * @Title: login
     * @Description: todo(登陆)
     * @param int $code 微信登录凭证
     * @return json
     * @author 若谷
     * @date 2019年5月22日
     * @throws
     */
    private function login($openid){
    	$model = new \app\common\model\Member;
    	$member = $model->where("openid",$openid)->find();
    	$token = md5(uniqid(microtime(true),true));
    	if ($member) {
            if (!$member['status']) {
                return false;
            }
    		$data = [
    			'id'        => $member['id'],
    			'token'     => $token,
    			'last_time' => time(),
    			'loginnum'  => $member['loginnum']+1,
    		];
    		$result = $model->allowField(true)->save($data, $data['id']);
    	}else{
    		$data = [
    			'openid'    => $openid,
    			'token'     => $token,
    			'last_time' => time(),
    		];
    		$result = $model->allowField(true)->save($data);
    	}
    	if ($result) {
    		return $token;
    	}else{
    		return false;
    	}
    }
}